package com.test29_文件;

import org.junit.Test;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 文件更名
 */
public class Demo05_FileRename {

    @Test
    public void test1() {
        File oldFile = new File("F:" + File.separator + "yootk.txt");   // 原始文件
        File newFile = new File("F:" + File.separator + "muyan.txt");   // 新的文件
        System.out.println("【文件更名处理】" + oldFile.renameTo(newFile));
    }

    @Test
    public void test2() throws Exception {
        // yootk-yyyyMMdd-编号.log
        File dir = new File("F:" + File.separator + "muyan" + File.separator + "logs" + File.separator);
        if (!dir.exists()) {
            dir.mkdirs();   // 如果不存在，创建目录
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        for (int x = 0; x < 100; x++) {
            File file = new File(dir, "yootk-"+sdf.format(new Date())+"-"+x+".log");
            file.createNewFile();   // 创建文件
        }
    }

    @Test
    public void test3() {
        File dir = new File("F:" + File.separator + "muyan" + File.separator + "logs" + File.separator);
        DirRenameUtil dirRenameUtil = new DirRenameUtil(dir);
        dirRenameUtil.rename();
    }
}

/**
 * 专属的命名工具类
 */
class DirRenameUtil {
    private File dir;   // 操作的目录地址
    private int sequenceLength; // 保存整体文件编号的最大长度
    private int fileCount = 0;

    public DirRenameUtil(File dir) {
        this.dir = dir;
        this.calcFileCount(dir);
        this.sequenceLength = String.valueOf(this.fileCount).length();
    }

    public void rename() {
        this.renameHandle(this.dir);
    }

    private void renameHandle(File file) {
        if (file.isDirectory()) {
            File[] list = file.listFiles();
            if (list != null) {
                for (File sub : list) {
                    this.renameHandle(sub);
                }
            }
        } else {
            if (file.isFile()) {
                // yootk-20211012-99.log
                String start = file.getPath().substring(0, file.getPath().lastIndexOf("-")+1);
                String num = file.getName().substring(file.getName().lastIndexOf("-")+1, file.getName().indexOf(".log"));
                File newFile = new File(start + addZero(num) + ".log");
                file.renameTo(newFile);
            }
        }
    }

    /** 长度补零 */
    private String addZero(String val) {
        StringBuffer buf = new StringBuffer(val);
        while (buf.length() != this.sequenceLength) {
            buf.insert(0, "0");
        }
        return buf.toString();
    }

    /** 统计文件的数量 */
    private void calcFileCount(File file) {
        if (file.isDirectory()) {
            File[] list = file.listFiles();
            if (list != null) {
                for (File sub : list) {
                    this.calcFileCount(sub);
                }
            }
        } else {
            if (file.isFile()) {
                this.fileCount++;
            }
        }
    }
}
